<?

//
// Establish the hierarchy comparing left role only to "lower" roles on the right
function recursive($reference, $storage, $start, $end){
	for($i = $start+1; $i < $end; $i++) {
		$short = preg_replace('/\s+/','',$reference[$start].$reference[$i]);
		$storage[$reference[$start]][$reference[$i]] = $start.$i; 
		$storage["TOC"][$reference[$start]][] = '<a class="toc'.$short.'" href="#'.$short.'">'.$reference[$i].'</a>';
		flush();
	}
	if($end-$start > 1) {
		return recursive($reference, $storage, $start+1, $end);
	}
	return $storage;
}


function keyroles(){
	$pairs[] = array('Administrator','ePortfolio');
	$pairs[] = array('Course Manager','Group Manager');
	$pairs[] = array('Instructor','Librarian');
	$pairs[] = array('Instructor','CEL Course Editor');
	$pairs[] = array('Instructor','Staff');
	$pairs[] = array('Instructor','TA - Level 4');
	$pairs[] = array('TA - Level 4','TA - Level 3');
	$pairs[] = array('TA - Level 3','TA - Level 2');
	$pairs[] = array('TA - Level 2','TA - Level 1.5');
	$pairs[] = array('TA - Level 1.5','TA - Level 1');
	$pairs[] = array('Student','TA - Level 3');
	$pairs[] = array('Student','TA - Level 2');
	$pairs[] = array('Student','TA - Level 1.5');
	$pairs[] = array('Student','TA - Level 1');
	$pairs[] = array('Student','Test Student');
	$pairs[] = array('Student','Past Student');
	$pairs[] = array('Student','Future Student');
	$pairs[] = array('Student','Guest Student');
	$pairs[] = array('Student','Observer');
	
	while(list(,$pair) = each($pairs)) {
		$short = preg_replace('/\s+/','',$pair[0].$pair[1]);
		$storage[$pair[0]][$pair[1]] = true; 
		$storage["TOC"][$pair[0]][] = '<a class="toc'.$short.'" href="#'.$short.'">'.$pair[1].'</a>';
	}
		
	return $storage;
}

function noCompareToc($TOC) {
	$html = '';
	while(list(,$role) = each($TOC)) {
		$short = preg_replace('/\s+/','',$role);
		$html .= '-<a class="toc'.$short.'" href="#'.$short.'">'.$role.'</a><br>'."\n";
	}
	return $html.'<br><br>';
}

function toolTOC($data, $theTool) {
	$toolPath = 'd2ladminhelp/le/roles_permissions/';

	$html = '<div class="actions">';
	$html .= '<BR><b><a target="_blank"href="'.$toolPath.strtolower(preg_replace('/\s+/','_',$theTool)).'_permissions.htm">'.$theTool.' Docs</a></b><BR><BR>';
	while(list($permission) = each($data)) {
		$short = preg_replace('/\s+/','',$permission);
		$html .= '-<a class="toc'.$short.'" href="#'.$short.'">'.$permission.'</a><br>';
	}
	return $html.'</div>';
}

function allToolsTOC($data) {
	$html = '<div class="actions">';
	while(list($permission) = each($data)) {
		$short = preg_replace('/\s+/','',$permission);
		$html .= '<a class="toc'.$short.'" href="#'.$short.'">'.$permission.'</a><br>';
	}
	return $html.'</div>';
}


function bigCompareToc($TOC) {
	$html = '<table width="100%" border="1" cellpadding="2" cellspacing="0" class="toc"><thead><tr>';
	while(list($role, $array) = each($TOC)) {
		$html .= '<th>'.$role.'</th>';
	}
	$html .= '</tr></thead>'."\n";
	$html .= '<tbody><tr>';
	reset($TOC);
	while(list($role, $array) = each($TOC)) {
		$html .= '<td valign="top">';
		while(list($key, $link) = each($array)) {
			$html .= '-'.$link.'<br>';
		}
		$html .= '</td>';
	}
	$html .= '</tr><tbody></table>';
	return $html;
}

function buildAllToolsTable($theSite, $outypes) {
	$translate = array(-1 => 'NA', 0 => '0', 1 => '1');
	$bgcolor = array(-1 => '#E6E6E6', 0 => '#FE2E2E', 1 => '#2EFE9A');
	$data = '';
	//
	// Formulate Query		
	$sql = sprintf("SELECT `R`.`Key`, concat(`SR`.`order`,'.',`R`.`Role`) AS `Role`, `R`.`Permission`, `R`.`OUType`, `R`.`Value`, `R`.`Tool` FROM `Roles` AS `R`, `SystemRoles` AS `SR` WHERE `R`.`Role`=`SR`.`roleName` AND `R`.`Site`=`SR`.`system` AND `R`.`Site`='%s' ORDER BY `R`.`Key`", mysql_real_escape_string($theSite));
	//	
    // Perform Query
    $result = mysql_query($sql);
	$num_rows = mysql_num_rows($result);

    // Check result
    // This shows the actual query sent to MySQL, and the error. Useful for debugging.
    if (!$result) {
          $message  = 'Invalid query: ' . mysql_error() . "\n";
          $message .= 'Whole query: ' . $sql;
          die($message);
    }

    // Use result
	while ($row = mysql_fetch_assoc($result)) {
		if(trim($row['Tool']).trim($row['Permission']) != "ScheduleImport events") {
			$data[$row['Tool'].' - '.$row['Permission']][$row['Role']][$row['OUType']] = $row['Value'];
		}
	}
	
	echo allToolsTOC($data);	
	while (list($permission,$roleArray) = each($data)) {
		echo '<br><b><a name="'.preg_replace('/\s+/','',$permission).'">'.$permission.'</a></b>';
		echo '<table border="1" cellpadding="2" cellspacing="0" width="100%">';
		echo '<thead><tr name="colHeader">';
		echo '<th>Role</th>';
		reset($outypes);
		while(list($key,$value) = each($outypes)) {
			echo '<th width="9%">'.$value.'</th>';
		}
		echo '</tr></thead><tbody>';
		natksort($roleArray);
		while(list($role, $valueArray) = each($roleArray)) {
			list(,$role) = explode(".",$role); 
			echo '<tr><td>'.$role.'</td>';
			while(list($ou, $value) = each($valueArray)) {
				echo '<td bgcolor="'.$bgcolor[$value].'">'.$translate[$value].'</td>';
			}
			echo '</tr>';
		}
		echo '</tbody></table><a class="actions" href="#top">Top</a><BR>';
	}
	
	mysql_free_result($result);
	echo '</div>';
}

function buildToolTable($theTool, $theSite, $outypes) {
	$translate = array(-1 => 'NA', 0 => '0', 1 => '1');
	$bgcolor = array(-1 => '#E6E6E6', 0 => '#FE2E2E', 1 => '#2EFE9A');
	//
	// Formulate Query		
	$sql = sprintf("SELECT `R`.`Key`, concat(`SR`.`order`,'.',`R`.`Role`) AS `Role`, `R`.`Permission`, `R`.`OUType`, `R`.`Value` FROM `Roles` AS `R`, `SystemRoles` AS `SR` WHERE `R`.`Role`=`SR`.`roleName` AND `R`.`Site`=`SR`.`system` AND `R`.`Tool`='%s' AND `R`.`Site`='%s' ORDER BY `R`.`Key`", mysql_real_escape_string($theTool), mysql_real_escape_string($theSite));
	
	//	
    // Perform Query
    $result = mysql_query($sql);
	$num_rows = mysql_num_rows($result);

    // Check result
    // This shows the actual query sent to MySQL, and the error. Useful for debugging.
    if (!$result) {
          $message  = 'Invalid query: ' . mysql_error() . "\n";
          $message .= 'Whole query: ' . $sql;
          die($message);
    }

    // Use result
	while ($row = mysql_fetch_assoc($result)) {
		$data[$row['Permission']][$row['Role']][$row['OUType']] = $row['Value'];
	}
	
	echo toolTOC($data, $theTool);	
	while (list($permission,$roleArray) = each($data)) {
		echo '<br><b><a name="'.preg_replace('/\s+/','',$permission).'">'.$permission.'</a></b>';
		echo '<table border="1" cellpadding="2" cellspacing="0" width="100%">';
		echo '<thead><tr name="colHeader">';
		echo '<th>Role</th>';
		reset($outypes);
		while(list($key,$value) = each($outypes)) {
			echo '<th width="9%">'.$value.'</th>';
		}
		echo '</tr></thead><tbody>';
		natksort($roleArray);
		while(list($role, $valueArray) = each($roleArray)) {
			list(,$role) = explode(".",$role); 
			echo '<tr><td>'.$role.'</td>';
			while(list($ou, $value) = each($valueArray)) {
				echo '<td bgcolor="'.$bgcolor[$value].'">'.$translate[$value].'</td>';
			}
			echo '</tr>';
		}
		echo '</tbody></table><a class="actions" href="#top">Top</a><BR>';
	}
	
	mysql_free_result($result);
	echo '</div>';
}

function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}
//
// Central processing and output function
function buildCompareTable($outype, $allvals, $leftRole, $leftSite, $rightRole, $rightSite) {
	
	$twoRoles = ($rightRole.$rightSite == "NoneNone") ? false : true;

	//
	// Formulate Query		
    if(strcmp($outype,"All") == 0) {
        $scope = " AND A.OUType = B.OUType";
    } else {
        $scope = sprintf(" AND A.OUType = '%s' AND A.OUType = B.OUType", mysql_real_escape_string($outype));
    }			

    if( strcmp($allvals,"All") == 0 ) {
        $diffs = "";
    } elseif ( strcmp($allvals,"Ineq") == 0 ) {
		$diffs =  " AND A.Value < B.Value";
	} else {
        $diffs = " AND A.Value<>B.Value";
    }			

	if($twoRoles) {
		$sql = sprintf("SELECT `A`.`Tool`, `A`.`Permission`, `A`.`OUType`, `A`.`Value` AS aval, `B`.`Value` AS bval FROM `Roles` AS A, `Roles` AS B WHERE `A`.`Permission` = `B`.`Permission` AND `A`.`Tool`=`B`.`Tool` AND `A`.`Site`='%s' AND `A`.`Role`='%s' AND `B`.`Site`='%s' AND `B`.`Role`='%s' ".$scope.$diffs, mysql_real_escape_string($leftSite), mysql_real_escape_string($leftRole), mysql_real_escape_string($rightSite), mysql_real_escape_string($rightRole) );
	} else {
		$sql = sprintf("SELECT `Tool`, `Permission`, `OUType`, `Value` AS aval FROM `Roles` WHERE `Site`='%s' AND `Role`='%s' ORDER BY `Key`", mysql_real_escape_string($leftSite), mysql_real_escape_string($leftRole) );	
		$rightRole = '';
	}
    // Perform Query
    $result = mysql_query($sql);
	$num_rows = mysql_num_rows($result);

	$divClass = ($num_rows > 0) ? "fullTable" : "emptyTable";

    // Check result
    // This shows the actual query sent to MySQL, and the error. Useful for debugging.
    if (!$result) {
          $message  = 'Invalid query: ' . mysql_error() . "\n";
          $message .= 'Whole query: ' . $sql;
          die($message);
    }

	echo '<div class="'.$divClass.'"><table class="actions" width="100%"><tr><td><b><a target="_blank" href="./csv/'.$leftSite.'/Edit Role_ '.$leftRole.' - University of Waterloo.pdf">'.$leftRole.'</a></b>';
	if($twoRoles) {
		$name = preg_replace('/\s+/','',$leftRole.$rightRole);
		echo '<a name="'.$name.'"> vs. </a>';
		echo '<b><a target="_blank" href="./csv/'.$rightSite.'/Edit Role_ '.$rightRole.' - University of Waterloo.pdf">'.$rightRole.'</a></b>';
	} else {
		$name = preg_replace('/\s+/','',$leftRole);
		echo '<a name="'.$name.'">&nbsp;</a>';
	} 
	echo '</td><td align="right"><label for="filter">Filter</label> <input type="text" class="filter" name="f'.$name.'" value="" id="f'.$name.'" /></td></tr></table>';
	echo '<table name="t'.$name.'" border="1" cellpadding="2" cellspacing="0" width="100%" class="compareTable">';
	echo '<thead><tr name="colHeader">';
	echo '<th>Num</th><th width="19%">Tool</th><th width="19%">Permission</th><th>OUType</th>';
	echo '<th width="19%">'.$leftRole.' on '. $leftSite.'</th>';
	if($twoRoles) {
		echo '<th width="19%">'.$rightRole.' on '.$rightSite.'</th><th>Ineq</th>';
	}
	echo '</tr></thead><tbody>';

    // Use result
    $i = 1;
	$color = "";
	$uneq = "&nbsp;";
	$toolPath = 'd2ladminhelp/le/roles_permissions/';
    while ($row = mysql_fetch_assoc($result)) {
		extract($row);
		if($Tool.$Permission != "ScheduleImport events") {			
			if($twoRoles) {
				if($row['aval'] < $row['bval']) {
					$uneq = "*";
				}
			}
        	echo '<tr><td>'.$i++.'</td><td><a target="_blank" href="'.$toolPath.strtolower(preg_replace('/\s+/','_',$Tool)).'_permissions.htm">'.$Tool.'</a></td><td>'.$Permission.'</td><td>'.$OUType.'</td><td>'.$aval.'</td>';
			if($twoRoles) {
				echo "<td>".$bval."</td>";
				echo "<td>".$uneq."</td>";
				$uneq = "&nbsp;";
			}
			echo "</tr>\n";
		}
    }
	mysql_free_result($result);
	echo '</tbody></table><a class="actions" href="#top">Top</a><BR>';
	echo '<style type="text/css">';
	echo 'a.toc'.preg_replace('/\s+/','',$leftRole.$rightRole).' { color:sienna; }';  
	echo '</style>';
	echo '</div>';
}

function buildExclude() {
	$sql = 'SELECT DISTINCT `roleName` FROM `SystemRoles`';
	$result = mysql_query($sql);
	// Check result
	// This shows the actual query sent to MySQL, and the error. Useful for debugging.
	if (!$result) {
	    $message  = 'Invalid query: ' . mysql_error() . "\n";
	    $message .= 'Whole query: ' . $sql;
	    die($message);
	}
	$string ='';
	while ($row = mysql_fetch_assoc($result)) {
		$string .= "AND `Permission` NOT LIKE '%".$row['roleName']."%' ";
	}	
	return $string;
}

function upgradeDiff() {
	echo '<table border="1" cellpadding="2" cellspacing="0" width="100%">';
	echo '<thead><th>Tool</th><th>Permission</th><th>9.2</th><th>9.4</th></thead><tbody>';
	//
	// Build Dropdowns
	$exclude = buildExclude();
	
	$sql = "SELECT * FROM `Roles` WHERE `Role` IN ('Administrator','Super Admin') $exclude ORDER BY `Key`";

	$result = mysql_query($sql);
	// Check result
	// This shows the actual query sent to MySQL, and the error. Useful for debugging.
	if (!$result) {
	    $message  = 'Invalid query: ' . mysql_error() . "\n";
	    $message .= 'Whole query: ' . $sql;
	    die($message);
	}

	while ($row = mysql_fetch_assoc($result)) {
		$comp[$row['Tool']][$row['Permission']][$row['Role']] = 1;
	}
	//
	// output it to screen
	while(list($tool, $perms) = each($comp)) {
		while(list($perm, $values) = each($perms)) {
			if(!array_key_exists('Administrator', $values)) {
				$values['Administrator'] = 0;
			}
			if(!array_key_exists('Super Admin', $values)) {
				$values['Super Admin'] = 0;
			}
			if($values['Administrator'] > $values['Super Admin']) {
				$bgcolor = ' bgcolor="#FE2E2E"';
			} elseif ($values['Administrator'] < $values['Super Admin']) {
				$bgcolor = ' bgcolor="#2EFE9A"';
			} else {
				$bgcolor = '';
			}
			echo '<tr'.$bgcolor.'>';
			echo '<td>'.$tool.'</td><td>'.$perm.'</td><td>'.$values['Administrator'].'</td><td>'.$values['Super Admin'].'</td>';
			echo '</tr>';
		}
	} 
	echo '</tbody></table>';
}

//
// Generic Dump function
function dump($var) {
  echo "<pre>";
  print_r($var);
  echo "</pre>\n";
  flush();
}

?>